package com.xinlong.service.impl;

import com.github.pagehelper.PageInfo;
import com.xinlong.entity.SchedulerJob;
import com.xinlong.service.SchedulerService;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SchedulerServiceImpl implements SchedulerService {

    @Autowired
    private Scheduler scheduler;


    public PageInfo<SchedulerJob> show(int page, int size, int triggerStatus) throws Exception {
        GroupMatcher<JobKey> matcher = GroupMatcher.anyGroup();

        Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
        List<SchedulerJob> jobList = new ArrayList<SchedulerJob>();

        for (JobKey jobKey : jobKeys) {
            List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
            for (Trigger trigger : triggers) {
                SchedulerJob job = new SchedulerJob();
                job.setId(trigger.getDescription());//description 放的是job的id
                job.setName(jobKey.getName());
                job.setGroup(jobKey.getGroup());
                job.setTrigger("触发器:" + trigger.getKey());
                Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                job.setStatus(triggerState.name());
                job.setClassName(scheduler.getJobDetail(trigger.getJobKey()).getJobClass()+"");

                if(job.getClassName().split(" ").length==2){
                    job.setClassName(job.getClassName().substring(job.getClassName().indexOf(" ")));
                }

                if (trigger instanceof CronTrigger) {
                    CronTrigger cronTrigger = (CronTrigger) trigger;
                    String cronExpression = cronTrigger.getCronExpression();
                    job.setCronExpression(cronExpression);
                }

                if(triggerStatus==0){
                    jobList.add(job);
                }else if(triggerStatus==1){
                    if(job.getStatus()==SchedulerJob.STATUS_NORMAL){
                        jobList.add(job);
                    }
                }else if(triggerStatus==2){
                    if(job.getStatus()==SchedulerJob.STATUS_PAUSE){
                        jobList.add(job);
                    }
                }

            }
        }
        //进行分页
        List<SchedulerJob> pageList = null;
        if(jobList.size()<((page-1)*size)+size){
           //获取当前页数量
          int number = jobList.size()-(page-1)*size;
           pageList = jobList.subList((page-1)*size,number);
        }else{
            pageList = jobList.subList((page-1)*size,((page-1)*size)+size);
        }
        PageInfo info = new PageInfo();
        info.setTotal(jobList.size());
        info.setList(pageList);
        info.setPageNum(page);
        info.setPageSize(size);
        info.setPages(jobList.size()%size==0?jobList.size()/size:jobList.size()/size+1);
        return info;
    }


    public int add(SchedulerJob job) throws Exception{
        if (job == null) {
            throw new Exception("Job不能为Null");
        }
        //通过Group和Name 获取TriggerKey
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getName(), job.getGroup());
        //获取Cron表达式
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        // 不存在，创建一个
        if (null == trigger) {
            Class clazz = Class.forName(job.getClassName());

            JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(job.getName(), job.getGroup()).build();

            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

            trigger = TriggerBuilder.newTrigger().withDescription(job.getId()).withIdentity(job.getName(), job.getGroup())
                    .withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
        } else {
            // Trigger已存在，那么更新相应的定时设置
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
            // 按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        }
        return SchedulerService.OPTION_SUCCESS;
    }



    public int delete(String name,String group)  throws Exception{
        JobDetail jobDetail =  scheduler.getJobDetail(new JobKey(name,group));
        if(null==jobDetail){
            return JOB_NOT_FOUND;
        }
        scheduler.deleteJob(jobDetail.getKey());
        return SchedulerService.OPTION_SUCCESS;
    }


    public int pause(String name, String group) throws Exception {
      JobDetail jobDetail =  scheduler.getJobDetail(new JobKey(name,group));

      if(null==jobDetail){
          return JOB_NOT_FOUND;
      }
      scheduler.pauseJob(jobDetail.getKey());
      return SchedulerService.OPTION_SUCCESS;
    }


    public int resume(String name, String group) throws Exception {
        JobDetail jobDetail =  scheduler.getJobDetail(new JobKey(name,group));

        if(null==jobDetail){
            return JOB_NOT_FOUND;
        }
        scheduler.resumeJob(jobDetail.getKey());
        return SchedulerService.OPTION_SUCCESS;
    }


    public int execute(String name, String group) throws Exception {
        JobDetail jobDetail =  scheduler.getJobDetail(new JobKey(name,group));

        if(null==jobDetail){
            return JOB_NOT_FOUND;
        }
        scheduler.triggerJob(jobDetail.getKey());
        return SchedulerService.OPTION_SUCCESS;
    }


    public SchedulerJob selByNameAndGroup(String name, String group) throws Exception {
        SchedulerJob job = new SchedulerJob();

        JobDetail jobDetail =  scheduler.getJobDetail(new JobKey(name,group));

        if(null== jobDetail){
            throw new Exception("Job不存在");
        }
        List<? extends Trigger> list = scheduler.getTriggersOfJob(jobDetail.getKey());
        for (Trigger temp:list){
            job.setTrigger(temp.getKey()+"");
            //获取Cron表达式
            CronTrigger trigger = (CronTrigger) temp;
            job.setCronExpression(trigger.getCronExpression());
            job.setId(trigger.getDescription());
        }
        job.setClassName(jobDetail.getJobClass()+"");


        if(job.getClassName().split(" ").length==2){
            job.setClassName(job.getClassName().substring(job.getClassName().indexOf(" ")));
        }


        job.setGroup(group);
        job.setName(name);
        return job;
    }
}
